home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / bash-1.12 / dist / execute_cmd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-21  |  77.1 KB  |  2,858 lines

  1. /* execute_command.c -- Execute a COMMAND structure. */
  2.  
  3. /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
  4.  
  5.    This file is part of GNU Bash, the Bourne Again SHell.
  6.  
  7.    Bash is free software; you can redistribute it and/or modify it
  8.    under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    Bash is distributed in the hope that it will be useful, but WITHOUT
  13.    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14.    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  15.    License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with Bash; see the file COPYING.  If not, write to the Free
  19.    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  20.  
  21. #include <stdio.h>
  22. #include <ctype.h>
  23. #include <sys/types.h>
  24. #include <sys/file.h>
  25. #include "posixstat.h"
  26. #include "filecntl.h"
  27. #include <signal.h>
  28.  
  29. #if !defined (SIGABRT)
  30. #define SIGABRT SIGIOT
  31. #endif
  32.  
  33. #include <sys/param.h>
  34. #include <errno.h>
  35.  
  36. #include "shell.h"
  37. #include "y.tab.h"
  38. #include "flags.h"
  39. #include "hash.h"
  40. #include "jobs.h"
  41.  
  42. #include "sysdefs.h"
  43. #include <glob/fnmatch.h>
  44.  
  45. int builtin_pipe_in = NO_PIPE;
  46. int builtin_pipe_out = NO_PIPE;
  47.  
  48. #if !defined (errno)
  49. extern int errno;
  50. #endif
  51.  
  52. extern int breaking, continuing, loop_level;
  53. extern int interactive, login_shell;
  54.  
  55. #if defined (JOB_CONTROL)
  56. extern int job_control;
  57. extern int set_job_control ();
  58. #endif /* JOB_CONTROL */
  59.  
  60. extern int getdtablesize ();
  61. extern int close ();
  62. extern char *strerror ();
  63. extern char *string_list ();
  64.  
  65. #if defined (USG)
  66. extern pid_t last_made_pid;
  67. #endif
  68.  
  69. extern WORD_LIST *expand_words (), *expand_word ();
  70. extern char *make_command_string ();
  71.  
  72. extern Function *find_shell_builtin (), *builtin_address ();
  73.  
  74. /* Static functions defined and used in this file. */
  75. #if defined (NOTDEF)
  76. /* Currently unused. */
  77. static void close_all_files ();
  78. #endif /* NOTDEF */
  79. static void close_pipes ();
  80. static void do_piping ();
  81. static int do_redirection_internal (), do_redirections ();
  82. static int expandable_redirection_filename ();
  83. static int execute_shell_script ();
  84. static void execute_disk_command ();
  85. static int execute_builtin_or_function ();
  86. static void execute_subshell_builtin_or_function ();
  87. static void cleanup_redirects (), cleanup_func_redirects ();
  88. static void bind_lastarg ();
  89. static int add_undo_redirect ();
  90. static void add_undo_close_redirect ();
  91. static char *find_user_command_internal ();
  92. static char *find_user_command_in_path ();
  93.  
  94. /* The value returned by the last synchronous command. */
  95. int last_command_exit_value = 0;
  96.  
  97. /* The list of redirections to preform which will undo the redirections
  98.    that I made in the shell. */
  99. REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
  100.  
  101. /* Use this as the function to call when adding unwind protects so we
  102.    don't need to know what free() returns. */
  103. static void
  104. vfree(s)
  105.      char *s;
  106. {
  107.   free (s);
  108. }
  109.  
  110. #define FD_BITMAP_DEFAULT_SIZE 32
  111. /* Functions to allocate and deallocate the structures used to pass
  112.    information from the shell to its children about file descriptors
  113.    to close. */
  114. struct fd_bitmap *
  115. new_fd_bitmap (size)
  116.      long size;
  117. {
  118.   struct fd_bitmap *ret;
  119.  
  120.   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
  121.  
  122.   ret->size = size;
  123.  
  124.   if (size)
  125.     {
  126.       ret->bitmap = (char *)xmalloc (size);
  127.       bzero (ret->bitmap, size);
  128.     }
  129.   else
  130.     ret->bitmap = (char *)NULL;
  131.   return (ret);
  132. }
  133.  
  134. void
  135. dispose_fd_bitmap (fdbp)
  136.      struct fd_bitmap *fdbp;
  137. {
  138.   if (fdbp->bitmap)
  139.     free (fdbp->bitmap);
  140.  
  141.   free (fdbp);
  142. }
  143.  
  144. void
  145. close_fd_bitmap (fdbp)
  146.      struct fd_bitmap *fdbp;
  147. {
  148.   register int i;
  149.  
  150.   if (fdbp)
  151.     {
  152.       for (i = 0; i < fdbp->size; i++)
  153.     if (fdbp->bitmap[i])
  154.       {
  155.         close (i);
  156.         fdbp->bitmap[i] = 0;
  157.       }
  158.     }
  159. }
  160.  
  161. /* Execute the command passed in COMMAND.  COMMAND is exactly what
  162.    read_command () places into GLOBAL_COMMAND.  See "shell.h" for the
  163.    details of the command structure.
  164.  
  165.    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
  166.    return values.  Executing a command with nothing in it returns
  167.    success. */
  168. execute_command (command)
  169.      COMMAND *command;
  170. {
  171.   struct fd_bitmap *fd_close_bmap;
  172.   int r;
  173.  
  174.   fd_close_bmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
  175.  
  176.   /* Just do the command, but not asynchronously. */
  177.   r = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, fd_close_bmap);
  178.   dispose_fd_bitmap (fd_close_bmap);
  179.  
  180. #if defined (PROCESS_SUBSTITUTION)
  181.   unlink_fifo_list ();
  182. #endif
  183.  
  184.   return r;
  185. }
  186.  
  187. /* Returns 1 if TYPE is a shell control structure type. */
  188. int
  189. shell_control_structure (type)
  190.      enum command_type type;
  191. {
  192.   switch (type)
  193.     {
  194.     case cm_for:
  195.     case cm_case:
  196.     case cm_while:
  197.     case cm_until:
  198.     case cm_if:
  199.     case cm_group:
  200.       return (1);
  201.  
  202.     default:
  203.       return (0);
  204.     }
  205. }
  206.  
  207. /* A function to use to unwind_protect the redirection undo list
  208.    for loops. */
  209. static void
  210. cleanup_redirects (list)
  211.      REDIRECT *list;
  212. {
  213.   do_redirections (list, 1, 0, 0);
  214.   dispose_redirects (list);
  215. }
  216.  
  217. /* Function to unwind_protect the redirections for functions and builtins. */
  218. static void
  219. cleanup_func_redirects (list)
  220.      REDIRECT *list;
  221. {
  222.   do_redirections (list, 1, 0, 0);
  223. }
  224.  
  225. #if defined (JOB_CONTROL)
  226. /* A function to restore the signal mask to its proper value when the shell
  227.    is interrupted or errors occur while creating a pipeline. */
  228. static int
  229. restore_signal_mask (set)
  230.      sigset_t set;
  231. {
  232.   return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
  233. }
  234. #endif /* JOB_CONTROL */
  235.  
  236. /* A debugging function that can be called from gdb, for instance. */
  237. open_files ()
  238. {
  239.   register int i;
  240.   int f, fd_table_size;
  241.  
  242.   fd_table_size = getdtablesize ();
  243.  
  244.   fprintf (stderr, "pid %d open files:", getpid ());
  245.   for (i = 3; i < fd_table_size; i++)
  246.     {
  247.       if ((f = fcntl (i, F_GETFD, 0)) != -1)
  248.     fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
  249.     }
  250.   fprintf (stderr, "\n");
  251. }
  252.  
  253. execute_command_internal (command, asynchronous, pipe_in, pipe_out, 
  254.               fds_to_close)
  255.      COMMAND *command;
  256.      int asynchronous;
  257.      int pipe_in, pipe_out;
  258.      struct fd_bitmap *fds_to_close;
  259. {
  260.   int exec_result = EXECUTION_SUCCESS;
  261.   int invert, ignore_return;
  262.   REDIRECT *my_undo_list;
  263.  
  264.   if (!command || breaking || continuing)
  265.     return (EXECUTION_SUCCESS);
  266.  
  267.   run_pending_traps ();
  268.  
  269.   invert = (command->flags & CMD_INVERT_RETURN) != 0;
  270.  
  271.   /* If a command was being explicitly run in a subshell, or if it is
  272.      a shell control-structure, and it has a pipe, then we do the command
  273.      in a subshell. */
  274.  
  275.   if ((command->flags & CMD_WANT_SUBSHELL) ||
  276.       (command->flags & CMD_FORCE_SUBSHELL)  ||
  277.       (shell_control_structure (command->type) &&
  278.        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
  279.     {
  280.       pid_t paren_pid;
  281.  
  282.       /* Fork a subshell, turn off the subshell bit, turn off job
  283.      control and call execute_command () on the command again. */
  284.       paren_pid = make_child (savestring (make_command_string (command)),
  285.                   asynchronous);
  286.       if (paren_pid == 0)
  287.     {
  288.       int user_subshell, return_code;
  289.  
  290.       user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
  291.       command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL);
  292.  
  293.       /* If a command is asynchronous in a subshell (like ( foo ) & or
  294.          the special case of an asynchronous GROUP command where the
  295.          the subshell bit is turned on down in case cm_group: below), 
  296.          turn off `asynchronous', so that two subshells aren't spawned.
  297.  
  298.          This seems semantically correct to me.  For example, 
  299.          ( foo ) & seems to say ``do the command `foo' in a subshell
  300.          environment, but don't wait for that subshell to finish'',
  301.          and "{ foo ; bar } &" seems to me to be like functions or
  302.          builtins in the background, which executed in a subshell
  303.          environment.  I just don't see the need to fork two subshells. */
  304.  
  305.       /* Don't fork again, we are already in a subshell. */
  306.       asynchronous = 0;
  307.  
  308.       /* Subshells are neither login nor interactive. */
  309.       login_shell = interactive = 0;
  310.  
  311. #if defined (JOB_CONTROL)
  312.       /* Delete all traces that there were any jobs running.  This is
  313.          only for subshells. */
  314.       without_job_control ();
  315. #endif /* JOB_CONTROL */
  316.       do_piping (pipe_in, pipe_out);
  317.  
  318.       if (fds_to_close)
  319.         close_fd_bitmap (fds_to_close);
  320.  
  321.       /* Do redirections, then dispose of them before recursive call. */
  322.       if (command->redirects)
  323.         {
  324.           if (!(do_redirections (command->redirects, 1, 0, 0) == 0))
  325.         exit (EXECUTION_FAILURE);
  326.  
  327.           dispose_redirects (command->redirects);
  328.           command->redirects = (REDIRECT *)NULL;
  329.         }
  330.  
  331.       return_code = execute_command_internal
  332.         (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
  333.  
  334.       /* If we were explicitly placed in a subshell with (), we need
  335.          to do the `shell cleanup' things, such as running traps[0]. */
  336.       if (user_subshell)
  337.         run_exit_trap ();
  338.  
  339.       exit (return_code);
  340.     }
  341.       else
  342.     {
  343.       close_pipes (pipe_in, pipe_out);
  344.  
  345.       /* If we are part of a pipeline, and not the end of the pipeline,
  346.          then we should simply return and let the last command in the
  347.          pipe be waited for.  If we are not in a pipeline, or are the
  348.          last command in the pipeline, then we wait for the subshell 
  349.          and return its exit status as usual. */
  350.       if (pipe_out != NO_PIPE)
  351.         return (EXECUTION_SUCCESS);
  352.  
  353.       stop_pipeline (asynchronous, (COMMAND *)NULL);
  354.  
  355.       if (!asynchronous)
  356.         {
  357.           last_command_exit_value = wait_for (paren_pid);
  358.  
  359.           /* If we have to, invert the return value. */
  360.           if (invert)
  361.         {
  362.           if (last_command_exit_value == EXECUTION_SUCCESS)
  363.             return (EXECUTION_FAILURE);
  364.           else
  365.             return (EXECUTION_SUCCESS);
  366.         }
  367.           else
  368.         return (last_command_exit_value);
  369.         }
  370.       else
  371.         {
  372.           if (interactive)
  373.         describe_pid (paren_pid);
  374.  
  375.           run_pending_traps ();
  376.  
  377.           return (EXECUTION_SUCCESS);
  378.         }
  379.     }
  380.     }
  381.  
  382.   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
  383.      redirection.)  */
  384.   do_redirections (command->redirects, 1, 1, 0);
  385.   my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
  386.  
  387.   begin_unwind_frame ("loop_redirections");
  388.  
  389.   if (my_undo_list)
  390.     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
  391.  
  392.   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
  393.  
  394.   switch (command->type)
  395.     {
  396.     case cm_for:
  397.       if (ignore_return)
  398.     command->value.For->flags |= CMD_IGNORE_RETURN;
  399.       exec_result = execute_for_command (command->value.For);
  400.       break;
  401.  
  402.     case cm_case:
  403.       if (ignore_return)
  404.     command->value.Case->flags |= CMD_IGNORE_RETURN;
  405.       exec_result = execute_case_command (command->value.Case);
  406.       break;
  407.  
  408.     case cm_while:
  409.       if (ignore_return)
  410.     command->value.While->flags |= CMD_IGNORE_RETURN;
  411.       exec_result = execute_while_command (command->value.While);
  412.       break;
  413.  
  414.     case cm_until:
  415.       if (ignore_return)
  416.     command->value.While->flags |= CMD_IGNORE_RETURN;
  417.       exec_result = execute_until_command (command->value.While);
  418.       break;
  419.  
  420.     case cm_if:
  421.       if (ignore_return)
  422.     command->value.If->flags |= CMD_IGNORE_RETURN;
  423.       exec_result = execute_if_command (command->value.If);
  424.       break;
  425.  
  426.     case cm_group:
  427.  
  428.       /* This code can be executed from either of two paths: an explicit
  429.      '{}' command, or via a function call.  If we are executed via a
  430.      function call, we have already taken care of the function being
  431.      executed in the background (down there in execute_simple_command ()),
  432.      and this command should *not* be marked as asynchronous.  If we
  433.      are executing a regular '{}' group command, and asynchronous == 1,
  434.      we must want to execute the whole command in the background, so we
  435.      need a subshell, and we want the stuff executed in that subshell
  436.      (this group command) to be executed in the foreground of that
  437.      subshell (i.e. there will not be *another* subshell forked).
  438.  
  439.      What we do is to force a subshell if asynchronous, and then call
  440.      execute_command_internal again with asynchronous still set to 1,
  441.      but with the original group command, so the printed command will
  442.      look right.
  443.  
  444.      The code above that handles forking off subshells will note that
  445.      both subshell and async are on, and turn off async in the child
  446.      after forking the subshell (but leave async set in the parent, so
  447.      the normal call to describe_pid is made).  This turning off
  448.      async is *crucial*; if it is not done, this will fall into an
  449.      infinite loop of executions through this spot in subshell after
  450.      subshell until the process limit is exhausted. */
  451.  
  452.       if (asynchronous)
  453.     {
  454.       command->flags |= CMD_FORCE_SUBSHELL;
  455.       exec_result =
  456.         execute_command_internal (command, 1, pipe_in, pipe_out,
  457.                       fds_to_close);
  458.     }
  459.       else
  460.     {
  461.       if (ignore_return && command->value.Group->command)
  462.         command->value.Group->command->flags |= CMD_IGNORE_RETURN;
  463.       exec_result =
  464.         execute_command_internal (command->value.Group->command,
  465.                       asynchronous, pipe_in, pipe_out,
  466.                       fds_to_close);
  467.     }
  468.       break;
  469.  
  470.     case cm_simple:
  471.       {
  472.     pid_t last_pid = last_made_pid;
  473.  
  474. #if defined (JOB_CONTROL)
  475.     extern int already_making_children;
  476. #endif /* JOB_CONTROL */
  477.     if (ignore_return && command->value.Simple)
  478.       command->value.Simple->flags |= CMD_IGNORE_RETURN;
  479.     exec_result =
  480.       execute_simple_command (command->value.Simple, pipe_in, pipe_out,
  481.                   asynchronous, fds_to_close);
  482.  
  483.     /* The temporary environment should be used for only the simple
  484.        command immediately following its definition. */
  485.     dispose_used_env_vars ();
  486.  
  487. #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
  488.     /* Reclaim memory allocated with alloca () on machines which
  489.        may be using the alloca emulation code. */
  490.     (void) alloca (0);
  491. #endif /* (Ultrix && mips) || !HAVE_ALLOCA */
  492.  
  493.     /* If we forked to do the command, then we must wait_for ()
  494.        the child. */
  495. #if defined (JOB_CONTROL)
  496.     if (already_making_children && pipe_out == NO_PIPE)
  497. #else
  498.       if (pipe_out == NO_PIPE)
  499. #endif /* JOB_CONTROL */
  500.         {
  501.           if (last_pid != last_made_pid)
  502.         {
  503.           stop_pipeline (asynchronous, (COMMAND *)NULL);
  504.  
  505.           if (asynchronous)
  506.             {
  507.               if (interactive)
  508.             describe_pid (last_made_pid);
  509.             }
  510.           else
  511. #if !defined (JOB_CONTROL)
  512.             /* Do not wait for asynchronous processes started from
  513.                startup files. */
  514.             if (last_made_pid != last_asynchronous_pid)
  515. #endif
  516.               /* When executing a shell function that executes other
  517.              commands, this causes the last simple command in
  518.              the function to be waited for twice. */
  519.               exec_result = wait_for (last_made_pid);
  520.         }
  521.         }
  522.       }
  523.       if (!ignore_return && exit_immediately_on_error && !invert &&
  524.       (exec_result != EXECUTION_SUCCESS))
  525.     {
  526.       last_command_exit_value = exec_result;
  527.       run_pending_traps ();
  528.       longjmp (top_level, EXITPROG);
  529.     }
  530.  
  531.       break;
  532.  
  533.     case cm_connection:
  534.       switch (command->value.Connection->connector)
  535.     {
  536.       /* Do the first command asynchronously. */
  537.     case '&':
  538.       {
  539.         COMMAND *tc = command->value.Connection->first;
  540.         if (ignore_return && tc)
  541.           tc->flags |= CMD_IGNORE_RETURN;
  542.  
  543. #if !defined (JOB_CONTROL)
  544.         {
  545.           REDIRECT *tr = 
  546.         make_redirection (0, r_inputa_direction,
  547.                   make_word ("/dev/null"));
  548.           tr->next = tc->redirects;
  549.           tc->redirects = tr;
  550.         }
  551. #endif /* !JOB_CONTROL */
  552.         exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out,
  553.                             fds_to_close);
  554.         if (command->value.Connection->second)
  555.           {
  556.         if (ignore_return && command->value.Connection->second)
  557.           command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
  558.  
  559.         exec_result =
  560.           execute_command_internal (command->value.Connection->second,
  561.                         asynchronous, pipe_in, pipe_out,
  562.                         fds_to_close);
  563.           }
  564.       }
  565.       break;
  566.  
  567.     case ';':
  568.       /* Just call execute command on both of them. */
  569.       if (ignore_return)
  570.         {
  571.           if (command->value.Connection->first)
  572.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  573.           if (command->value.Connection->second)
  574.         command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
  575.         }
  576.       execute_command (command->value.Connection->first);
  577.       exec_result =
  578.         execute_command_internal (command->value.Connection->second,
  579.                       asynchronous, pipe_in, pipe_out,
  580.                       fds_to_close);
  581.       break;
  582.  
  583.     case '|':
  584.       {
  585.         int prev, fildes[2], new_bitmap_size, dummyfd;
  586.         COMMAND *cmd;
  587.         struct fd_bitmap *fd_bitmap;
  588.  
  589. #if defined (JOB_CONTROL)
  590.         sigset_t set, oset;
  591.         BLOCK_CHILD (set, oset);
  592. #endif /* JOB_CONTROL */
  593.  
  594.         prev = pipe_in;
  595.         cmd = command;
  596.  
  597.         while (cmd &&
  598.            cmd->type == cm_connection &&
  599.            cmd->value.Connection &&
  600.            cmd->value.Connection->connector == '|')
  601.           {
  602.         /* Make a pipeline between the two commands. */
  603.         if (pipe (fildes) < 0)
  604.           {
  605.             report_error ("pipe error: %s", strerror (errno));
  606. #if defined (JOB_CONTROL)
  607.             terminate_current_pipeline ();
  608.             kill_current_pipeline ();
  609. #endif /* JOB_CONTROL */
  610.             last_command_exit_value = EXECUTION_FAILURE;
  611.             /* The unwind-protects installed below will take care
  612.                of closing all of the open file descriptors. */
  613.             throw_to_top_level ();
  614.           }
  615.         else
  616.           {
  617.             /* Here is a problem: with the new file close-on-exec
  618.                code, the read end of the pipe (fildes[0]) stays open
  619.                in the first process, so that process will never get a
  620.                SIGPIPE.  There is no way to signal the first process
  621.                that it should close fildes[0] after forking, so it
  622.                remains open.  No SIGPIPE is ever sent because there
  623.                is still a file descriptor open for reading connected
  624.                to the pipe.  We take care of that here.  This passes
  625.                around a bitmap of file descriptors that must be
  626.                closed after making a child process in
  627.                execute_simple_command. */
  628.  
  629.             /* We need fd_bitmap to be at least as big as fildes[0].
  630.                If fildes[0] is less than fds_to_close->size, then
  631.                use fds_to_close->size. */
  632.  
  633.             if (fildes[0] < fds_to_close->size)
  634.               new_bitmap_size = fds_to_close->size;
  635.             else
  636.               new_bitmap_size = fildes[0] + 8;
  637.  
  638.             fd_bitmap = new_fd_bitmap (new_bitmap_size);
  639.  
  640.             /* Now copy the old information into the new bitmap. */
  641.             bcopy (fds_to_close->bitmap, fd_bitmap->bitmap,
  642.                fds_to_close->size);
  643.  
  644.             /* And mark the pipe file descriptors to be closed. */
  645.             fd_bitmap->bitmap[fildes[0]] = 1;
  646.  
  647.             /* In case there are pipe or out-of-processes errors, we
  648.                want all these file descriptors to be closed when
  649.                unwind-protects are run, and the storage used for the
  650.                bitmaps freed up. */
  651.             begin_unwind_frame ("pipe-file-descriptors");
  652.             add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
  653.             add_unwind_protect (close_fd_bitmap, fd_bitmap);
  654.             if (prev >= 0)
  655.               add_unwind_protect (close, prev);
  656.             dummyfd = fildes[1];
  657.             add_unwind_protect (close, dummyfd);
  658.  
  659. #if defined (JOB_CONTROL)
  660.             add_unwind_protect (restore_signal_mask, oset);
  661. #endif /* JOB_CONTROL */
  662.  
  663.             if (ignore_return && cmd->value.Connection->first)
  664.               cmd->value.Connection->first->flags |=
  665.             CMD_IGNORE_RETURN;
  666.             execute_command_internal
  667.               (cmd->value.Connection->first, asynchronous, prev,
  668.                fildes[1], fd_bitmap);
  669.  
  670.             if (prev >= 0)
  671.               close (prev);
  672.             
  673.             prev = fildes[0];
  674.             close (fildes[1]);
  675.  
  676.             dispose_fd_bitmap (fd_bitmap);
  677.             discard_unwind_frame ("pipe-file-descriptors");
  678.           }
  679.         cmd = cmd->value.Connection->second;
  680.           }
  681.  
  682.         /* Now execute the rightmost command in the pipeline.  */
  683.         if (ignore_return && cmd)
  684.           cmd->flags |= CMD_IGNORE_RETURN;
  685.         exec_result =
  686.           execute_command_internal
  687.         (cmd, asynchronous, prev, pipe_out, fds_to_close);
  688.  
  689.         if (prev >= 0)
  690.           close (prev);
  691.  
  692. #if defined (JOB_CONTROL)
  693.         UNBLOCK_CHILD (oset);
  694. #endif
  695.       }
  696.       break;
  697.  
  698.     case AND_AND:
  699.       if (asynchronous)
  700.         {
  701.           /* If we have something like `a && b &', run the && stuff in a
  702.          subshell.  Force a subshell and just call
  703.          execute_command_internal again.  Leave asynchronous on
  704.          so that we get a report from the parent shell about the
  705.          background job. */
  706.           command->flags |= CMD_FORCE_SUBSHELL;
  707.           exec_result = execute_command_internal (command, 1, pipe_in,
  708.                   pipe_out, fds_to_close);
  709.           break;
  710.         }
  711.  
  712.       /* Execute the first command.  If the result of that is successful,
  713.          then execute the second command, otherwise return. */
  714.  
  715.       if (command->value.Connection->first)
  716.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  717.  
  718.       exec_result = execute_command (command->value.Connection->first);
  719.       if (exec_result == EXECUTION_SUCCESS)
  720.         {
  721.           if (ignore_return && command->value.Connection->second)
  722.         command->value.Connection->second->flags |=
  723.           CMD_IGNORE_RETURN;
  724.  
  725.           exec_result =
  726.         execute_command (command->value.Connection->second);
  727.         }
  728.       break;
  729.  
  730.     case OR_OR:
  731.       if (asynchronous)
  732.         {
  733.           /* If we have something like `a || b &', run the || stuff in a
  734.          subshell.  Force a subshell and just call
  735.          execute_command_internal again.  Leave asynchronous on
  736.          so that we get a report from the parent shell about the
  737.          background job. */
  738.           command->flags |= CMD_FORCE_SUBSHELL;
  739.           exec_result = execute_command_internal (command, 1, pipe_in,
  740.                   pipe_out, fds_to_close);
  741.           break;
  742.         }
  743.  
  744.       /* Execute the first command.  If the result of that is successful,
  745.          then return, otherwise execute the second command. */
  746.  
  747.       if (command->value.Connection->first)
  748.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  749.  
  750.       exec_result = execute_command (command->value.Connection->first);
  751.       if (exec_result != EXECUTION_SUCCESS)
  752.         {
  753.           if (ignore_return && command->value.Connection->second)
  754.         command->value.Connection->second->flags |=
  755.           CMD_IGNORE_RETURN;
  756.  
  757.           exec_result =
  758.         execute_command (command->value.Connection->second);
  759.         }
  760.  
  761.       break;
  762.  
  763.     default:
  764.       programming_error ("Bad connector `%d'!",
  765.                  command->value.Connection->connector);
  766.       longjmp (top_level, DISCARD);
  767.       break;
  768.     }
  769.       break;
  770.  
  771.     case cm_function_def:
  772.       exec_result = intern_function (command->value.Function_def->name,
  773.                      command->value.Function_def->command);
  774.       break;
  775.  
  776.     default:
  777.       programming_error
  778.     ("execute_command: Bad command type `%d'!", command->type);
  779.     }
  780.  
  781.   if (my_undo_list)
  782.     {
  783.       do_redirections (my_undo_list, 1, 0, 0);
  784.       dispose_redirects (my_undo_list);
  785.     }
  786.  
  787.   discard_unwind_frame ("loop_redirections");
  788.  
  789.   /* Invert the return value if we have to */
  790.   if (invert)
  791.     {
  792.       if (exec_result == EXECUTION_SUCCESS)
  793.     exec_result = EXECUTION_FAILURE;
  794.       else
  795.     exec_result = EXECUTION_SUCCESS;
  796.     }
  797.  
  798.   last_command_exit_value = exec_result;
  799.   run_pending_traps ();
  800.   return (last_command_exit_value);
  801. }
  802.  
  803. /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
  804.    DO command; DONE */
  805. execute_for_command (for_command)
  806.      FOR_COM *for_command;
  807. {
  808.   /* I just noticed that the Bourne shell leaves word_desc bound to the
  809.      last name in word_list after the FOR statement is done.  This seems
  810.      wrong to me; I thought that the variable binding should be lexically
  811.      scoped, i.e., only would last the duration of the FOR command.  This
  812.      behaviour can be gotten by turning on the lexical_scoping switch. */
  813.  
  814.   register WORD_LIST *releaser, *list;
  815.   WORD_DESC *temp = for_command->name;
  816.   char *identifier;
  817.   SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
  818.   int retval = EXECUTION_SUCCESS;
  819.   extern int dispose_words ();
  820.   extern int dispose_variable ();
  821.  
  822.   if (!check_identifier (temp))
  823.     return (EXECUTION_FAILURE);
  824.  
  825.   loop_level++;
  826.   identifier = temp->word;
  827.  
  828.   list = releaser = expand_words (for_command->map_list, 0);
  829.  
  830.   begin_unwind_frame ("for");
  831.   add_unwind_protect (dispose_words, releaser);
  832.  
  833.   if (lexical_scoping)
  834.     {
  835.       old_value = copy_variable (find_variable (identifier));
  836.       if (old_value)
  837.     add_unwind_protect (dispose_variable, old_value);
  838.     }
  839.  
  840.   while (list)
  841.     {
  842.       QUIT;
  843.       bind_variable (identifier, list->word->word);
  844.       if (for_command->flags & CMD_IGNORE_RETURN)
  845.     for_command->action->flags |= CMD_IGNORE_RETURN;
  846.       execute_command (for_command->action);
  847.       retval = last_command_exit_value;
  848.       QUIT;
  849.  
  850.       if (breaking)
  851.     {
  852.       breaking--; 
  853.       break;
  854.     }
  855.  
  856.       if (continuing)
  857.     {
  858.       continuing--;
  859.       if (continuing)
  860.         break;
  861.     }
  862.  
  863.       list = list->next;
  864.     }
  865.  
  866.   loop_level--;
  867.  
  868.   if (lexical_scoping)
  869.     {
  870.       if (!old_value)
  871.     makunbound (identifier, shell_variables);
  872.       else
  873.     {
  874.       SHELL_VAR *new_value;
  875.  
  876.       new_value = bind_variable (identifier, value_cell(old_value));
  877.       new_value->attributes = old_value->attributes;
  878.     }
  879.     }
  880.  
  881.   run_unwind_frame ("for");
  882.   return (retval);
  883. }
  884.  
  885. /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
  886.    The pattern_list is a linked list of pattern clauses; each clause contains
  887.    some patterns to compare word_desc against, and an associated command to
  888.    execute. */
  889. execute_case_command (case_command)
  890.      CASE_COM *case_command;
  891. {
  892.   extern int dispose_words ();
  893.  
  894.   register WORD_LIST *list;
  895.   WORD_LIST *wlist;
  896.   PATTERN_LIST *clauses;
  897.   char *word;
  898.   int retval;
  899.  
  900.   wlist = expand_word (case_command->word, 0);
  901.   clauses = case_command->clauses;
  902.   word = (wlist) ? string_list (wlist) : savestring ("");
  903.   retval = EXECUTION_SUCCESS;
  904.  
  905.   begin_unwind_frame ("case");
  906.   add_unwind_protect (dispose_words, wlist);
  907.   add_unwind_protect ((Function *)vfree, word);
  908.  
  909.   while (clauses)
  910.     {
  911.       QUIT;
  912.       list = clauses->patterns;
  913.       while (list)
  914.     {
  915.       WORD_LIST *es = expand_word (list->word, 0);
  916.       char *pattern = (es) ? es->word->word : "";
  917.  
  918.       if (fnmatch (pattern, word, FNM_NOESCAPE) != FNM_NOMATCH)
  919.         {
  920.           dispose_words (es);
  921.           if (clauses->action && 
  922.           (case_command->flags & CMD_IGNORE_RETURN))
  923.         clauses->action->flags |= CMD_IGNORE_RETURN;
  924.           execute_command (clauses->action);
  925.           retval = last_command_exit_value;
  926.           goto exit_command;
  927.         }
  928.       dispose_words (es);
  929.       list = list->next;
  930.       QUIT;
  931.     }
  932.       clauses = clauses->next;
  933.     }
  934.  exit_command:
  935.   run_unwind_frame ("case");
  936.   return (retval);
  937. }
  938.  
  939. #define CMD_WHILE 0
  940. #define CMD_UNTIL 1
  941.  
  942. /* The WHILE command.  Syntax: WHILE test DO action; DONE.
  943.    Repeatedly execute action while executing test produces
  944.    EXECUTION_SUCCESS. */
  945. execute_while_command (while_command)
  946.      WHILE_COM *while_command;
  947. {
  948.   return (execute_while_or_until (while_command, CMD_WHILE));
  949. }
  950.  
  951. /* UNTIL is just like WHILE except that the test result is negated. */
  952. execute_until_command (while_command)
  953.      WHILE_COM *while_command;
  954. {
  955.   return (execute_while_or_until (while_command, CMD_UNTIL));
  956. }
  957.  
  958. /* The body for both while and until.  The only difference between the
  959.    two is that the test value is treated differently.  TYPE is
  960.    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
  961.    be EXECUTION_SUCCESS if no commands in the body are executed, and
  962.    the status of the last command executed in the body otherwise. */
  963. execute_while_or_until (while_command, type)
  964.      WHILE_COM *while_command;
  965.      int type;
  966. {
  967.   extern int breaking;
  968.   extern int continuing;
  969.   int commands_executed = 0;
  970.   int return_value;
  971.  
  972.   loop_level++;
  973.   while_command->test->flags |= CMD_IGNORE_RETURN;
  974.  
  975.   while (1)
  976.     {
  977.       return_value = execute_command (while_command->test);
  978.  
  979.       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
  980.     break;
  981.       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
  982.     break;
  983.  
  984.       QUIT;
  985.       commands_executed = 1;
  986.  
  987.       if (while_command->flags & CMD_IGNORE_RETURN)
  988.     while_command->action->flags |= CMD_IGNORE_RETURN;
  989.       execute_command (while_command->action);
  990.  
  991.       QUIT;
  992.  
  993.       if (breaking)
  994.     {
  995.       breaking--;
  996.       break;
  997.     }
  998.  
  999.       if (continuing)
  1000.     {
  1001.       continuing--;
  1002.       if (continuing)
  1003.         break;
  1004.     }
  1005.     }
  1006.   loop_level--;
  1007.  
  1008.   if (commands_executed)
  1009.     return (last_command_exit_value);
  1010.   else
  1011.     return (EXECUTION_SUCCESS);
  1012. }
  1013.  
  1014. /* IF test THEN command [ELSE command].
  1015.    IF also allows ELIF in the place of ELSE IF, but
  1016.    the parser makes *that* stupidity transparent. */
  1017. execute_if_command (if_command)
  1018.      IF_COM *if_command;
  1019. {
  1020.   int return_value;
  1021.  
  1022.   if_command->test->flags |= CMD_IGNORE_RETURN;
  1023.   return_value = execute_command (if_command->test);
  1024.  
  1025.   if (return_value == EXECUTION_SUCCESS)
  1026.     {
  1027.       QUIT;
  1028.       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
  1029.       if_command->true_case->flags |= CMD_IGNORE_RETURN;
  1030.       return (execute_command (if_command->true_case));
  1031.     }
  1032.   else
  1033.     {
  1034.       QUIT;
  1035.  
  1036.       if (if_command->false_case &&
  1037.       (if_command->flags & CMD_IGNORE_RETURN))
  1038.     {
  1039.       if_command->false_case->flags |= CMD_IGNORE_RETURN;
  1040.     }
  1041.  
  1042.       return (execute_command (if_command->false_case));
  1043.     }
  1044. }
  1045.  
  1046. /* The name of the command that is currently being executed.
  1047.    `test' needs this, for example. */
  1048. char *this_command_name;
  1049.  
  1050. static void
  1051. bind_lastarg (arg)
  1052.      char *arg;
  1053. {
  1054.   SHELL_VAR *var;
  1055.  
  1056.   if (!arg)
  1057.     arg = "";
  1058.   var = bind_variable ("_", arg);
  1059.   var->attributes &= ~att_exported;
  1060. }
  1061.  
  1062. /* For catching RETURN in a function. */
  1063. int return_catch_flag = 0;
  1064. int return_catch_value;
  1065. jmp_buf return_catch;
  1066.  
  1067. /* The meaty part of all the executions.  We have to start hacking the
  1068.    real execution of commands here.  Fork a process, set things up,
  1069.    execute the command. */
  1070. execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
  1071.      SIMPLE_COM *simple_command;
  1072.      int pipe_in, pipe_out;
  1073.      struct fd_bitmap *fds_to_close;
  1074. {
  1075.   extern int command_string_index, variable_context, line_number;
  1076.   extern char *the_printed_command;
  1077.   extern pid_t last_command_subst_pid;
  1078.   WORD_LIST *expand_words (), *copy_word_list ();
  1079.   WORD_LIST *words, *lastword;
  1080.   char *command_line, *lastarg;
  1081.   int first_word_quoted, result;
  1082.   pid_t old_last_command_subst_pid;
  1083.  
  1084.   result = EXECUTION_SUCCESS;
  1085.  
  1086.   /* If we're in a function, update the pseudo-line-number information. */
  1087.   if (variable_context)
  1088.     line_number++;
  1089.  
  1090.   /* Remember what this command line looks like at invocation. */
  1091.   command_string_index = 0;
  1092.   print_simple_command (simple_command);
  1093.   command_line = (char *)alloca (1 + strlen (the_printed_command));
  1094.   strcpy (command_line, the_printed_command);
  1095.  
  1096.   first_word_quoted =
  1097.     simple_command->words ? simple_command->words->word->quoted : 0;
  1098.  
  1099.   old_last_command_subst_pid = last_command_subst_pid;
  1100.  
  1101.   /* If we are re-running this as the result of executing the `command'
  1102.      builtin, do not expand the command words a second time. */
  1103.   if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
  1104.     words = expand_words (simple_command->words);
  1105.   else
  1106.     words = copy_word_list (simple_command->words);
  1107.  
  1108.   lastarg = (char *)NULL;
  1109.   begin_unwind_frame ("simple-command");
  1110.  
  1111.   /* It is possible for WORDS not to have anything left in it.
  1112.      Perhaps all the words consisted of `$foo', and there was
  1113.      no variable `$foo'. */
  1114.   if (words)
  1115.     {
  1116.       extern int dispose_words ();
  1117.       extern Function *last_shell_builtin, *this_shell_builtin;
  1118.       Function *builtin;
  1119.       SHELL_VAR *func;
  1120.       char *auto_resume_value;
  1121.  
  1122.       if (echo_command_at_execute)
  1123.     {
  1124.       extern char *indirection_level_string ();
  1125.       char *line = string_list (words);
  1126.  
  1127.       if (line && *line)
  1128.         fprintf (stderr, "%s%s\n", indirection_level_string (), line);
  1129.  
  1130.       if (line)
  1131.         free (line);
  1132.     }
  1133.  
  1134.       if (simple_command->flags & CMD_NO_FUNCTIONS)
  1135.     func = (SHELL_VAR *)NULL;
  1136.       else
  1137.     func = find_function (words->word->word);
  1138.  
  1139.       add_unwind_protect (dispose_words, words);
  1140.  
  1141.       QUIT;
  1142.  
  1143.       /* Bind the last word in this command to "$_" after execution. */
  1144.       for (lastword = words; lastword->next; lastword = lastword->next);
  1145.       lastarg = lastword->word->word;
  1146.  
  1147. #if defined (JOB_CONTROL)
  1148.       /* Is this command a job control related thing? */
  1149.       if (words->word->word[0] == '%')
  1150.     {
  1151.       int result;
  1152.  
  1153.       if (async)
  1154.         this_command_name = "bg";
  1155.       else
  1156.         this_command_name = "fg";
  1157.           
  1158.       last_shell_builtin = this_shell_builtin;
  1159.       this_shell_builtin = builtin_address (this_command_name);
  1160.       result = (*this_shell_builtin) (words);
  1161.       goto return_result;
  1162.     }
  1163.  
  1164.       /* One other possiblilty.  The user may want to resume an existing job.
  1165.      If they do, find out whether this word is a candidate for a running
  1166.      job. */
  1167.       if ((auto_resume_value = get_string_value ("auto_resume")) &&
  1168.       !first_word_quoted &&
  1169.       !words->next &&
  1170.       words->word->word[0] &&
  1171.       !simple_command->redirects &&
  1172.       pipe_in == NO_PIPE &&
  1173.       pipe_out == NO_PIPE &&
  1174.       !async)
  1175.     {
  1176.       char *word = words->word->word;
  1177.       register int i, wl = strlen (word), exact;
  1178.  
  1179.       exact = strcmp (auto_resume_value, "exact") == 0;
  1180.       for (i = job_slots - 1; i > -1; i--)
  1181.         {
  1182.           if (jobs[i])
  1183.         {
  1184.           register PROCESS *p = jobs[i]->pipe;
  1185.           do
  1186.             {
  1187.               if ((JOBSTATE (i) == JSTOPPED) &&
  1188.               (strncmp (p->command, word,
  1189.                     exact ? strlen (p->command) : wl) == 0))
  1190.             {
  1191.               int started_status;
  1192.  
  1193.               run_unwind_frame ("simple-command");
  1194.               last_shell_builtin = this_shell_builtin;
  1195.               this_shell_builtin = builtin_address ("fg");
  1196.  
  1197.               started_status = start_job (i, 1);
  1198.  
  1199.               if (started_status < 0)
  1200.                 return (EXECUTION_FAILURE);
  1201.               else
  1202.                 return (started_status);
  1203.             }
  1204.               p = p->next;
  1205.             }
  1206.           while (p != jobs[i]->pipe);
  1207.         }
  1208.         }
  1209.     }
  1210. #endif /* JOB_CONTROL */
  1211.  
  1212.       /* Remember the name of this command globally. */
  1213.       this_command_name = words->word->word;
  1214.  
  1215.       QUIT;
  1216.  
  1217.       /* Not a running job.  Do normal command processing. */
  1218.       maybe_make_export_env ();
  1219.  
  1220.       /* This command could be a shell builtin or a user-defined function.
  1221.      If so, and we have pipes, then fork a subshell in here.  Else, just
  1222.      do the command. */
  1223.  
  1224.       if (func)
  1225.     builtin = (Function *)NULL;
  1226.       else
  1227.     builtin = find_shell_builtin (this_command_name);
  1228.  
  1229.       last_shell_builtin = this_shell_builtin;
  1230.       this_shell_builtin = builtin;
  1231.  
  1232.       if (builtin || func)
  1233.     {
  1234.       put_command_name_into_env (this_command_name);
  1235.       if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
  1236.         {
  1237.           if (make_child (savestring (command_line), async) == 0)
  1238.         {
  1239.           execute_subshell_builtin_or_function
  1240.             (words, simple_command->redirects, builtin, func,
  1241.              pipe_in, pipe_out, async, fds_to_close,
  1242.              simple_command->flags);
  1243.         }
  1244.           else
  1245.         {
  1246.           close_pipes (pipe_in, pipe_out);
  1247.           goto return_result;
  1248.         }
  1249.         }
  1250.       else
  1251.         {
  1252.           result = execute_builtin_or_function
  1253.         (words, builtin, func, simple_command->redirects, fds_to_close,
  1254.          simple_command->flags);
  1255.  
  1256.           goto return_result;
  1257.         }
  1258.     }
  1259.  
  1260.       execute_disk_command (words, simple_command->redirects, command_line,
  1261.                 pipe_in, pipe_out, async, fds_to_close);
  1262.  
  1263.       goto return_result;
  1264.     }
  1265.   else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
  1266.     {
  1267.       /* We have a null command, but we really want a subshell to take
  1268.      care of it.  Just fork, do piping and redirections, and exit. */
  1269.       if (make_child (savestring (""), async) == 0)
  1270.     {
  1271.       do_piping (pipe_in, pipe_out);
  1272.  
  1273.       if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
  1274.         exit (EXECUTION_SUCCESS);
  1275.       else
  1276.         exit (EXECUTION_FAILURE);
  1277.     }
  1278.       else
  1279.     {
  1280.       close_pipes (pipe_in, pipe_out);
  1281.       result = EXECUTION_SUCCESS;
  1282.       goto return_result;
  1283.     }
  1284.     }
  1285.   else
  1286.     {
  1287.       /* Even if there aren't any command names, pretend to do the
  1288.      redirections that are specified.  The user expects the side
  1289.      effects to take place.  If the redirections fail, then return
  1290.      failure.  Otherwise, if a command substitution took place while
  1291.      expanding the command or a redirection, return the value of that
  1292.      substition.  Otherwise, return EXECUTION_SUCCESS. */
  1293.  
  1294.       if (do_redirections (simple_command->redirects, 0, 0, 0) != 0)
  1295.     result = EXECUTION_FAILURE;
  1296.       else if (old_last_command_subst_pid != last_command_subst_pid)
  1297.     result = last_command_exit_value;
  1298.       else
  1299.     result = EXECUTION_SUCCESS;
  1300.     }
  1301.  
  1302.  return_result:
  1303.   bind_lastarg (lastarg);
  1304.   run_unwind_frame ("simple-command");
  1305.   return (result);
  1306. }
  1307.  
  1308. /* Execute a shell builtin or function in a subshell environment.  This
  1309.    routine does not return; it only calls exit().  If BUILTIN is non-null,
  1310.    it points to a function to call to execute a shell builtin; otherwise
  1311.    VAR points at the body of a function to execute.  WORDS is the arguments
  1312.    to the command, REDIRECTS specifies redirections to perform before the
  1313.    command is executed. */
  1314. static void
  1315. execute_subshell_builtin_or_function (words, redirects, builtin, var,
  1316.                       pipe_in, pipe_out, async, fds_to_close,
  1317.                       flags)
  1318.      WORD_LIST *words;
  1319.      REDIRECT *redirects;
  1320.      Function *builtin;
  1321.      SHELL_VAR *var;
  1322.      int pipe_in, pipe_out, async;
  1323.      struct fd_bitmap *fds_to_close;
  1324.      int flags;
  1325. {
  1326.   extern int login_shell, interactive;
  1327. #if defined (JOB_CONTROL)
  1328.   extern int jobs_builtin ();
  1329. #endif /* JOB_CONTROL */
  1330.  
  1331.   /* A subshell is neither a login shell nor interactive. */
  1332.   login_shell = interactive = 0;
  1333.  
  1334. #if defined (JOB_CONTROL)
  1335.   /* Eradicate all traces of job control after we fork the subshell, so
  1336.      all jobs begun by this subshell are in the same process group as
  1337.      the shell itself. */
  1338.  
  1339.   /* Allow the output of `jobs' to be piped. */
  1340.   if (builtin == jobs_builtin && !async &&
  1341.       (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
  1342.     kill_current_pipeline ();
  1343.   else
  1344.     without_job_control ();
  1345. #endif /* JOB_CONTROL */
  1346.  
  1347.   do_piping (pipe_in, pipe_out);
  1348.  
  1349.   if (fds_to_close)
  1350.     close_fd_bitmap (fds_to_close);
  1351.  
  1352.   if (do_redirections (redirects, 1, 0, 0) != 0)
  1353.     exit (EXECUTION_FAILURE);
  1354.  
  1355.   if (builtin)
  1356.     {
  1357.       extern jmp_buf top_level;
  1358.       int result;
  1359.  
  1360.       /* Save the values of pipe_in and pipe_out for
  1361.      possible later use by parse_and_execute (). */
  1362.       builtin_pipe_in = pipe_in;
  1363.       builtin_pipe_out = pipe_out;
  1364.  
  1365.       /* Give builtins a place to jump back to on failure,
  1366.      so we don't go back up to main(). */
  1367.       result = setjmp (top_level);
  1368.  
  1369.       if (result)
  1370.     exit (result);
  1371.       else
  1372.     exit ((*builtin) (words->next));
  1373.     }
  1374.   else
  1375.     {
  1376.       extern int variable_context, line_number;
  1377.       extern void dispose_command ();
  1378.       COMMAND *fc, *tc;
  1379.       int result, return_val;
  1380.  
  1381.       tc = (COMMAND *)function_cell (var);
  1382.       fc = (COMMAND *)NULL;
  1383.  
  1384.       remember_args (words->next, 1);
  1385.       line_number = 0;
  1386. #if defined (JOB_CONTROL)
  1387.       stop_pipeline (async, (COMMAND *)NULL);
  1388. #endif
  1389.  
  1390.       begin_unwind_frame ("subshell_function_calling");
  1391.       unwind_protect_int (variable_context);
  1392.       unwind_protect_int (return_catch_flag);
  1393.       unwind_protect_jmp_buf (return_catch);
  1394.       add_unwind_protect (dispose_command, fc);
  1395.  
  1396.       /* We can do this because function bodies are always guaranteed to
  1397.      be group commands, according to the grammar in parse.y.  If we
  1398.      don't do this now, execute_command_internal will graciously fork
  1399.      another subshell for us, and we'll lose contact with the rest of
  1400.      the pipeline and fail to get any SIGPIPE that might be sent. */
  1401.  
  1402.       if (tc->type == cm_group)
  1403.     fc = (COMMAND *)copy_command (tc->value.Group->command);
  1404.       else
  1405.     fc = (COMMAND *)copy_command (tc);
  1406.  
  1407.       if (fc && (flags & CMD_IGNORE_RETURN))
  1408.     fc->flags |= CMD_IGNORE_RETURN;
  1409.  
  1410.       /* result = execute_command (fc); doesn't work.
  1411.      We need to explicitly specify the pipes in and out so that they
  1412.      are closed in all the processes that rely on their being closed.
  1413.      If they are not, it is possible to not get the SIGPIPE that we
  1414.      need to kill all the processes sharing the pipe. */
  1415.  
  1416.       variable_context++;
  1417.       return_catch_flag++;
  1418.       return_val = setjmp (return_catch);
  1419.  
  1420.       if (return_val)
  1421.     result = return_catch_value;
  1422.       else
  1423.     result =
  1424.       execute_command_internal (fc, 0, pipe_in, pipe_out, fds_to_close);
  1425.  
  1426.       run_unwind_frame ("subshell_function_calling");
  1427.  
  1428.       exit (result);
  1429.     }
  1430. }
  1431.  
  1432. /* Execute a builtin or function in the current shell context.  If BUILTIN
  1433.    is non-null, it is the builtin command to execute, otherwise VAR points
  1434.    to the body of a function.  WORDS are the command's arguments, REDIRECTS
  1435.    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
  1436.    file descriptors to close.
  1437.  
  1438.    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
  1439.    not undone before this function returns. */
  1440. static int
  1441. execute_builtin_or_function (words, builtin, var, redirects,
  1442.                  fds_to_close, flags)
  1443.      WORD_LIST *words;
  1444.      Function *builtin;
  1445.      SHELL_VAR *var;
  1446.      REDIRECT *redirects;
  1447.      struct fd_bitmap *fds_to_close;
  1448.      int flags;
  1449. {
  1450.   extern int exec_builtin (), eval_builtin ();
  1451.   int result = EXECUTION_FAILURE;
  1452.   int redir_result;
  1453.   REDIRECT *saved_undo_list;
  1454.  
  1455.   redir_result = do_redirections (redirects, 1, 1, 0);
  1456.  
  1457.   if (redir_result != 0)
  1458.     return (EXECUTION_FAILURE);
  1459.  
  1460.   saved_undo_list = redirection_undo_list;
  1461.  
  1462.   /* Calling the "exec" builtin changes redirections forever. */
  1463.   if (builtin == exec_builtin)
  1464.     {
  1465.       dispose_redirects (saved_undo_list);
  1466.       saved_undo_list = (REDIRECT *)NULL;
  1467.     }
  1468.   else
  1469.     {
  1470.       begin_unwind_frame ("saved redirects");
  1471.       add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
  1472.     }
  1473.  
  1474.   redirection_undo_list = (REDIRECT *)NULL;
  1475.  
  1476.   if (builtin)
  1477.     {
  1478.       int old_e_flag = exit_immediately_on_error;
  1479.  
  1480.       /* The eval builtin calls parse_and_execute, which does not know about
  1481.      the setting of flags, and always calls the execution functions with
  1482.      flags that will exit the shell on an error if -e is set.  If the
  1483.      eval builtin is being called, and we're supposed to ignore the exit
  1484.      value of the command, we turn the -e flag off ourselves, then
  1485.      restore it when the command completes. */
  1486.       if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
  1487.     {
  1488.       begin_unwind_frame ("eval_builtin");
  1489.       unwind_protect_int (exit_immediately_on_error);
  1490.       exit_immediately_on_error = 0;
  1491.     }
  1492.  
  1493.       result = ((*builtin) (words->next));
  1494.  
  1495.       if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
  1496.     {
  1497.       exit_immediately_on_error += old_e_flag;
  1498.       discard_unwind_frame ("eval_builtin");
  1499.     }
  1500.     }
  1501.   else
  1502.     {
  1503.       extern void dispose_command ();
  1504.       extern int pop_context ();
  1505.       extern int line_number;
  1506.       int return_val;
  1507.       COMMAND *tc;
  1508.  
  1509.       tc = (COMMAND *)copy_command (function_cell (var));
  1510.       if (tc && (flags & CMD_IGNORE_RETURN))
  1511.     tc->flags |= CMD_IGNORE_RETURN;
  1512.  
  1513.       begin_unwind_frame ("function_calling");
  1514.       push_context ();
  1515.       add_unwind_protect (pop_context, (char *)NULL);
  1516.       add_unwind_protect (dispose_command, (char *)tc);
  1517.       unwind_protect_int (return_catch_flag);
  1518.       unwind_protect_int (line_number);
  1519.       unwind_protect_jmp_buf (return_catch);
  1520.  
  1521.       /* Note the second argument of "1", meaning that we discard
  1522.      the current value of "$*"!  This is apparently the right thing. */
  1523.       remember_args (words->next, 1);
  1524.  
  1525.       line_number = 0;
  1526.       return_catch_flag++;
  1527.       return_val =  setjmp (return_catch);
  1528.  
  1529.       if (return_val)
  1530.     result = return_catch_value;
  1531.       else
  1532.     result = 
  1533.       execute_command_internal (tc, 0, NO_PIPE, NO_PIPE, fds_to_close);
  1534.  
  1535.       run_unwind_frame ("function_calling");
  1536.     }
  1537.  
  1538.   redirection_undo_list = saved_undo_list;
  1539.   if (builtin != exec_builtin)
  1540.     discard_unwind_frame ("saved redirects");
  1541.   do_redirections (redirection_undo_list, 1, 0, 0);
  1542.  
  1543.   return (result);
  1544. }
  1545.  
  1546. /* Execute a simple command that is hopefully defined in a disk file
  1547.    somewhere.
  1548.  
  1549.    1) fork ()
  1550.    2) connect pipes
  1551.    3) look up the command
  1552.    4) do redirections
  1553.    5) execve ()
  1554.    6) If the execve failed, see if the file has executable mode set.
  1555.    If so, and it isn't a directory, then execute its contents as
  1556.    a shell script.
  1557.  
  1558.    Note that the filename hashing stuff has to take place up here,
  1559.    in the parent.  This is probably why the Bourne style shells
  1560.    don't handle it, since that would require them to go through
  1561.    this gnarly hair, for no good reason.  */
  1562. static void
  1563. execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
  1564.               async, fds_to_close)
  1565.      WORD_LIST *words;
  1566.      REDIRECT *redirects;
  1567.      char *command_line;
  1568.      int pipe_in, pipe_out, async;
  1569.      struct fd_bitmap *fds_to_close;
  1570. {
  1571.   char **make_word_array (), *find_user_command (),
  1572.   *find_hashed_filename ();
  1573.  
  1574.   char *hashed_file = (char *)NULL, *command, **args;
  1575.  
  1576.   /* Don't waste time trying to find hashed data for a pathname
  1577.      that is already completely specified. */
  1578.  
  1579.   if (!absolute_program (words->word->word))
  1580.     hashed_file = find_hashed_filename (words->word->word);
  1581.  
  1582.   if (hashed_file)
  1583.     command = savestring (hashed_file);
  1584.   else
  1585.     {
  1586.       /* A command containing a slash is not looked up in PATH. */
  1587.       if (absolute_program (words->word->word))
  1588.     command = savestring (words->word->word);
  1589.       else
  1590.     command = find_user_command (words->word->word);
  1591.  
  1592.       if (command && !hashing_disabled)
  1593.     {
  1594.       extern int dot_found_in_search;
  1595.       /* A command name containing a slash is not saved in the
  1596.          hash table. */
  1597.       if (!absolute_program (words->word->word))
  1598.         remember_filename (words->word->word, command, dot_found_in_search);
  1599.       /* Increase the number of hits to 1. */
  1600.       find_hashed_filename (words->word->word);
  1601.     }
  1602.     }
  1603.  
  1604.   if (command)
  1605.     {
  1606.       put_command_name_into_env (command);
  1607.     }
  1608.  
  1609.   /* We have to make the child before we check for the non-existance
  1610.      of COMMAND, since we want the error messages to be redirected. */
  1611.  
  1612.   if (make_child (savestring (command_line), async) == 0)
  1613.     {
  1614.       do_piping (pipe_in, pipe_out);
  1615.  
  1616.       /* Execve expects the command name to be in args[0].  So we
  1617.      leave it there, in the same format that the user used to
  1618.      type it in. */
  1619.       args = make_word_array (words);
  1620.  
  1621.       if (do_redirections (redirects, 1, 0, 0) != 0)
  1622.     exit (EXECUTION_FAILURE);
  1623.  
  1624.       if (!command)
  1625.     {
  1626.       report_error ("%s: command not found", args[0]);
  1627.       exit (EXECUTION_FAILURE);
  1628.     }
  1629.  
  1630.       /* This functionality is now provided by close-on-exec of the
  1631.      file descriptors manipulated by redirection and piping.
  1632.      Some file descriptors still need to be closed in all children
  1633.      because of the way bash does pipes; fds_to_close is a 
  1634.      bitmap of all such file descriptors. */
  1635.       if (fds_to_close)
  1636.     close_fd_bitmap (fds_to_close);
  1637.  
  1638.       signal (SIGCHLD, SIG_DFL);
  1639.       exit (shell_execve (command, args, export_env));
  1640.     }
  1641.   else
  1642.     {
  1643.       /* Make sure that the pipes are closed in the parent. */
  1644.       close_pipes (pipe_in, pipe_out);
  1645.       free (command);
  1646.     }
  1647. }
  1648.  
  1649. /* If the operating system on which we're running does not handle
  1650.    the #! executable format, then help out.  SAMPLE is the text read
  1651.    from the file, SAMPLE_LEN characters.  COMMAND is the name of
  1652.    the script; it and ARGS, the arguments given by the user, will
  1653.    become arguments to the specified interpreter.  ENV is the environment
  1654.    to pass to the interpreter.
  1655.  
  1656.    The word immediately following the #! is the interpreter to execute.
  1657.    A single argument to the interpreter is allowed. */
  1658. static int
  1659. execute_shell_script (sample, sample_len, command, args, env)
  1660.      unsigned char *sample;
  1661.      int sample_len;
  1662.      char *command;
  1663.      char **args, **env;
  1664. {
  1665.   extern char *shell_name;
  1666.   register int i;
  1667.   char *execname, *firstarg;
  1668.   int start, size_increment, larry;
  1669.  
  1670.   /* Find the name of the interpreter to exec. */
  1671.   for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
  1672.     ;
  1673.  
  1674.   for (start = i;
  1675.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1676.        i++)
  1677.     ;
  1678.  
  1679.   execname = (char *)xmalloc (1 + (i - start));
  1680.   strncpy (execname, sample + start, i - start);
  1681.   execname[i - start] = '\0';
  1682.   size_increment = 1;
  1683.  
  1684.   /* Now the argument, if any. */
  1685.   firstarg = (char *)NULL;
  1686.   for (start = i;
  1687.        whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1688.        i++)
  1689.     ;
  1690.  
  1691.   /* If there is more text on the line, then it is an argument for the
  1692.      interpreter. */
  1693.   if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
  1694.     {
  1695.       for (start = i;
  1696.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1697.        i++)
  1698.     ;
  1699.       firstarg = (char *)xmalloc (1 + (i - start));
  1700.       strncpy (firstarg, sample + start, i - start);
  1701.       firstarg[i - start] = '\0';
  1702.  
  1703.       size_increment = 2;
  1704.     }
  1705.  
  1706.   larry = array_len (args) + size_increment;
  1707.  
  1708.   args = (char **)xrealloc (args, (1 + larry) * sizeof (char *));
  1709.  
  1710.   for (i = larry - 1; i; i--)
  1711.     args[i] = args[i - size_increment];
  1712.  
  1713.   args[0] = execname;
  1714.   if (firstarg)
  1715.     {
  1716.       args[1] = firstarg;
  1717.       args[2] = command;
  1718.     }
  1719.   else
  1720.     args[1] = command;
  1721.  
  1722.   args[larry] = (char *)NULL;
  1723.  
  1724.   return (shell_execve (execname, args, env));
  1725. }
  1726.  
  1727. /* Call execve (), handling interpreting shell scripts, and handling
  1728.    exec failures. */
  1729. int
  1730. shell_execve (command, args, env)
  1731.      char *command;
  1732.      char **args, **env;
  1733. {
  1734. #if defined (isc386) && defined (_POSIX_SOURCE)
  1735.   __setostype (0);        /* Turn on USGr3 semantics. */
  1736.   execve (command, args, env);
  1737.   __setostype (1);        /* Turn the POSIX semantics back on. */
  1738. #else
  1739.   execve (command, args, env);
  1740. #endif /* !(isc386 && _POSIX_SOURCE) */
  1741.  
  1742.   /* If we get to this point, then start checking out the file.
  1743.      Maybe it is something we can hack ourselves. */
  1744.   {
  1745.     struct stat finfo;
  1746.  
  1747.     if (errno != ENOEXEC)
  1748.       {
  1749.     if ((stat (command, &finfo) == 0) &&
  1750.         (S_ISDIR (finfo.st_mode)))
  1751.       report_error ("%s: is a directory", args[0]);
  1752.     else
  1753.       file_error (command);
  1754.  
  1755.     return (EXECUTION_FAILURE);
  1756.       }
  1757.     else
  1758.       {
  1759.     /* This file is executable.
  1760.        If it begins with #!, then help out people with losing operating
  1761.        systems.  Otherwise, check to see if it is a binary file by seeing
  1762.        if the first line (or up to 30 characters) are in the ASCII set.
  1763.        Execute the contents as shell commands. */
  1764.     extern char *shell_name;
  1765.     int larray = array_len (args) + 1;
  1766.     int i, should_exec = 0;
  1767.  
  1768.     {
  1769.       int fd = open (command, O_RDONLY);
  1770.       if (fd != -1)
  1771.         {
  1772.           unsigned char sample[80];
  1773.           int sample_len = read (fd, &sample[0], 80);
  1774.  
  1775.           /* Is this supposed to be an executable script? */
  1776.           /* If so, the format of the line is "#! interpreter [argument]".
  1777.          A single argument is allowed.  The BSD kernel restricts
  1778.          the length of the entire line to 32 characters (32 bytes
  1779.          being the size of the BSD exec header), but we allow 80
  1780.          characters. */
  1781.  
  1782.           if (sample[0] == '#' && sample[1] == '!')
  1783.         {
  1784.           close (fd);
  1785.           return (execute_shell_script (sample, sample_len,
  1786.                           command, args, env));
  1787.         }
  1788. #if defined (NOTDEF)
  1789. #if defined (HAVE_CSH) && ( defined (Bsd) || defined (Ultrix) )
  1790.           /* If this system has Csh, then keep the old
  1791.          BSD semantics. */
  1792.           else if (sample_len > 0 && sample[0] == '#')
  1793.         {
  1794.           /* Scripts starting with a # are for Csh. */
  1795.           shell_name = savestring ("/bin/csh");
  1796.           should_exec = 1;
  1797.         }
  1798. #endif /* HAVE_CSH */
  1799. #endif /* NOTDEF */
  1800.           else
  1801.         {
  1802.           if (sample_len != -1)
  1803.             if (check_binary_file (sample, sample_len))
  1804.               {
  1805.             report_error ("%s: cannot execute binary file",
  1806.                       command);
  1807.             return (EX_BINARY_FILE);
  1808.               }
  1809.         }
  1810.           close (fd);
  1811.         }
  1812.     }
  1813. #if defined (JOB_CONTROL)
  1814.     /* Forget about the way that job control was working. We are
  1815.        in a subshell. */
  1816.     without_job_control ();
  1817. #endif /* JOB_CONTROL */
  1818. #if defined (ALIAS)
  1819.     /* Forget about any aliases that we knew of.  We are in a subshell. */
  1820.     delete_all_aliases ();
  1821. #endif /* ALIAS */
  1822.     /* Insert the name of this shell into the argument list. */
  1823.     args = (char **)xrealloc (args, (1 + larray) * sizeof (char *));
  1824.  
  1825.     for (i = larray - 1; i; i--)
  1826.       args[i] = args[i - 1];
  1827.  
  1828.     args[0] = shell_name;
  1829.     args[1] = command;
  1830.     args[larray] = (char *)NULL;
  1831.  
  1832.     if (args[0][0] == '-')
  1833.       args[0]++;
  1834.  
  1835.     if (should_exec)
  1836.       {
  1837.         struct stat finfo;
  1838.  
  1839. #if defined (isc386) && defined (_POSIX_SOURCE)
  1840.         __setostype (0);    /* Turn on USGr3 semantics. */
  1841.         execve (shell_name, args, env);
  1842.         __setostype (1);    /* Turn the POSIX semantics back on. */
  1843. #else
  1844.         execve (shell_name, args, env);
  1845. #endif /* isc386 && _POSIX_SOURCE */
  1846.  
  1847.         /* Oh, no!  We couldn't even exec this! */
  1848.         if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
  1849.           report_error ("%s: is a directory", args[0]);
  1850.         else
  1851.           file_error (args[0]);
  1852.  
  1853.         return (EXECUTION_FAILURE);
  1854.       }
  1855.     else
  1856.       {
  1857.         extern jmp_buf subshell_top_level;
  1858.         extern int subshell_argc;
  1859.         extern char **subshell_argv;
  1860.         extern char **subshell_envp;
  1861.  
  1862.         subshell_argc = larray;
  1863.         subshell_argv = args;
  1864.         subshell_envp = env;
  1865.         longjmp (subshell_top_level, 1);
  1866.       }
  1867.       }
  1868.   }
  1869. }
  1870.  
  1871. /* Currently unused. */
  1872. #if defined (NOTDEF)
  1873. static void
  1874. close_all_files ()
  1875. {
  1876.   register int i, fd_table_size;
  1877.  
  1878.   fd_table_size = getdtablesize ();
  1879.  
  1880.   for (i = 3; i < fd_table_size; i++)
  1881.     close (i);
  1882. }
  1883. #endif /* NOTDEF */
  1884.  
  1885. static void
  1886. close_pipes (in, out)
  1887.      int in, out;
  1888. {
  1889.   if (in >= 0) close (in);
  1890.   if (out >= 0) close (out);
  1891. }
  1892.  
  1893. /* Redirect input and output to be from and to the specified pipes.
  1894.    NO_PIPE and REDIRECT_BOTH are handled correctly. */
  1895. static void
  1896. do_piping (pipe_in, pipe_out)
  1897.      int pipe_in, pipe_out;
  1898. {
  1899.   if (pipe_in != NO_PIPE)
  1900.     {
  1901.       dup2 (pipe_in, 0);
  1902.       close (pipe_in);
  1903.     }
  1904.   if (pipe_out != NO_PIPE)
  1905.     {
  1906.       dup2 (pipe_out, 1);
  1907.       close (pipe_out);
  1908.  
  1909.       if (pipe_out == REDIRECT_BOTH)
  1910.     dup2 (1, 2);
  1911.     }
  1912. }
  1913.  
  1914. /* Defined in flags.c.  Non-zero means don't overwrite existing files. */
  1915. extern int noclobber;
  1916.  
  1917. #define AMBIGUOUS_REDIRECT -1
  1918. #define NOCLOBBER_REDIRECT -2
  1919. /* Perform the redirections on LIST.  If FOR_REAL, then actually make
  1920.    input and output file descriptors, otherwise just do whatever is
  1921.    neccessary for side effecting.  INTERNAL says to remember how to
  1922.    undo the redirections later, if non-zero.  If SET_CLEXEC is non-zero,
  1923.    file descriptors opened in do_redirection () have their close-on-exec
  1924.    flag set. */
  1925. static int
  1926. do_redirections (list, for_real, internal, set_clexec)
  1927.      REDIRECT *list;
  1928.      int for_real, internal;
  1929. {
  1930.   register int error;
  1931.   register REDIRECT *temp = list;
  1932.  
  1933.   if (internal && redirection_undo_list)
  1934.     {
  1935.       dispose_redirects (redirection_undo_list);
  1936.       redirection_undo_list = (REDIRECT *)NULL;
  1937.     }
  1938.  
  1939.   while (temp)
  1940.     {
  1941.       extern char *strerror ();
  1942.  
  1943.       error = do_redirection_internal (temp, for_real, internal, set_clexec);
  1944.  
  1945.       if (error)
  1946.     {
  1947.       char *redirection_expand (), *itos ();
  1948.       char *filename;
  1949.  
  1950.       if (expandable_redirection_filename (temp))
  1951.         {
  1952.           filename = redirection_expand (temp->redirectee.filename);
  1953.           if (!filename)
  1954.         filename = savestring ("");
  1955.         }
  1956.       else
  1957.         filename = itos (temp->redirectee.dest);
  1958.  
  1959.       switch (error)
  1960.         {
  1961.         case AMBIGUOUS_REDIRECT:
  1962.           report_error ("%s: Ambiguous redirect", filename);
  1963.           break;
  1964.  
  1965.         case NOCLOBBER_REDIRECT:
  1966.           report_error ("%s: Cannot clobber existing file", filename);
  1967.           break;
  1968.  
  1969.         default:
  1970.           report_error ("%s: %s", filename, strerror (error));
  1971.           break;
  1972.         }
  1973.  
  1974.       free (filename);
  1975.       return (error);
  1976.     }
  1977.  
  1978.       temp = temp->next;
  1979.     }
  1980.   return (0);
  1981. }
  1982.  
  1983. /* Return non-zero if the redirection pointed to by REDIRECT has a
  1984.    redirectee.filename that can be expanded. */
  1985. static int
  1986. expandable_redirection_filename (redirect)
  1987.      REDIRECT *redirect;
  1988. {
  1989.   int result;
  1990.  
  1991.   switch (redirect->instruction)
  1992.     {
  1993.     case r_output_direction:
  1994.     case r_appending_to:
  1995.     case r_input_direction:
  1996.     case r_inputa_direction:
  1997.     case r_err_and_out:
  1998.     case r_input_output:
  1999.     case r_output_force:
  2000.     case r_duplicating_input_word:
  2001.     case r_duplicating_output_word:
  2002.       result = 1;
  2003.       break;
  2004.  
  2005.     default:
  2006.       result = 0;
  2007.     }
  2008.   return (result);
  2009. }
  2010.  
  2011. /* Expand the word in WORD returning a string.  If WORD expands to
  2012.    multiple words (or no words), then return NULL. */
  2013. char *
  2014. redirection_expand (word)
  2015.      WORD_DESC *word;
  2016. {
  2017.   char *result;
  2018.   WORD_LIST *make_word_list (), *expand_words_no_vars ();
  2019.   WORD_LIST *tlist1, *tlist2;
  2020.  
  2021.   tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
  2022.   tlist2 = expand_words_no_vars (tlist1);
  2023.   dispose_words (tlist1);
  2024.  
  2025.   if (!tlist2 || tlist2->next)
  2026.     {
  2027.       /* We expanded to no words, or to more than a single word.
  2028.      Dispose of the word list and return NULL. */
  2029.       if (tlist2)
  2030.     dispose_words (tlist2);
  2031.       return ((char *)NULL);
  2032.     }
  2033.   result = string_list (tlist2);
  2034.   dispose_words (tlist2);
  2035.   return (result);
  2036. }
  2037.  
  2038. /* Do the specific redirection requested.  Returns errno in case of error.
  2039.    If FOR_REAL is zero, then just do whatever is neccessary to produce the
  2040.    appropriate side effects.   REMEMBERING, if non-zero, says to remember
  2041.    how to undo each redirection.  If SET_CLEXEC is non-zero, then
  2042.    we set all file descriptors > 2 that we open to be close-on-exec.  */
  2043. static int
  2044. do_redirection_internal (redirect, for_real, remembering, set_clexec)
  2045.      REDIRECT *redirect;
  2046.      int for_real, remembering;
  2047. {
  2048.   WORD_DESC *redirectee = redirect->redirectee.filename;
  2049.   int fd, redirector = redirect->redirector;
  2050.   char *redirectee_word;
  2051.   enum r_instruction ri = redirect->instruction;
  2052.   REDIRECT *new_redirect;
  2053.  
  2054.   if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
  2055.     {
  2056.       /* We have [N]>&WORD or [N]<&WORD.  Expand WORD, then translate
  2057.      the redirection into a new one and continue. */
  2058.       redirectee_word = redirection_expand (redirectee);
  2059.  
  2060.       if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
  2061.     {
  2062.       new_redirect = make_redirection (redirector, r_close_this, 0);
  2063.     }
  2064.       else if (all_digits (redirectee_word))
  2065.     {
  2066.       if (ri == r_duplicating_input_word)
  2067.         {
  2068.           new_redirect = make_redirection
  2069.         (redirector, r_duplicating_input, atoi (redirectee_word));
  2070.         }
  2071.       else
  2072.         {
  2073.           new_redirect = make_redirection
  2074.         (redirector, r_duplicating_output, atoi (redirectee_word));
  2075.         }
  2076.     }
  2077.       else if (ri == r_duplicating_output_word && redirector == 1)
  2078.     {
  2079.       new_redirect = make_redirection
  2080.         (1, r_err_and_out, make_word (redirectee_word));
  2081.     }
  2082.       else
  2083.     {
  2084.       free (redirectee_word);
  2085.       return (AMBIGUOUS_REDIRECT);
  2086.     }
  2087.  
  2088.       free (redirectee_word);
  2089.  
  2090.       /* Set up the variables needed by the rest of the function from the
  2091.      new redirection. */
  2092.       if (new_redirect->instruction == r_err_and_out)
  2093.     {
  2094.       char *alloca_hack;
  2095.  
  2096.       /* Copy the word without allocating any memory that must be
  2097.          explicitly freed. */
  2098.       redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
  2099.       bcopy (new_redirect->redirectee.filename,
  2100.          redirectee, sizeof (WORD_DESC));
  2101.  
  2102.       alloca_hack = (char *)
  2103.         alloca (1 + strlen (new_redirect->redirectee.filename->word));
  2104.       redirectee->word = alloca_hack;
  2105.       strcpy (redirectee->word, new_redirect->redirectee.filename->word);
  2106.     }
  2107.       else
  2108.     /* It's guaranteed to be an integer, and shouldn't be freed. */
  2109.     redirectee = new_redirect->redirectee.filename;
  2110.  
  2111.       redirector = new_redirect->redirector;
  2112.       ri = new_redirect->instruction;
  2113.  
  2114.       /* Overwrite the flags element of the old redirect with the new value. */
  2115.       redirect->flags = new_redirect->flags;
  2116.       dispose_redirects (new_redirect);
  2117.     }
  2118.  
  2119.   switch (ri)
  2120.     {
  2121.     case r_output_direction:
  2122.     case r_appending_to:
  2123.     case r_input_direction:
  2124.     case r_inputa_direction:
  2125.     case r_err_and_out:        /* command &>filename */
  2126.     case r_input_output:
  2127.     case r_output_force:
  2128.  
  2129.       if (!(redirectee_word = redirection_expand (redirectee)))
  2130.     return (AMBIGUOUS_REDIRECT);
  2131.  
  2132.       /* If we are in noclobber mode, you are not allowed to overwrite
  2133.      existing files.  Check first. */
  2134.       if (noclobber && (ri == r_output_direction ||
  2135.               ri == r_input_output ||
  2136.               ri == r_err_and_out))
  2137.       {
  2138.     struct stat buf;
  2139.     if ((stat (redirectee_word, &buf) == 0) &&
  2140.         (S_ISREG (buf.st_mode)))
  2141.       return (NOCLOBBER_REDIRECT);
  2142.       }
  2143.  
  2144.       fd = open (redirectee_word, redirect->flags, 0666);
  2145. #if defined (AFS_CREATE_BUG)
  2146.       if (fd < 0 && errno == EACCES)
  2147.     fd = open (redirectee_word, (redirect->flags & ~O_CREAT), 0666);
  2148. #endif /* AFS_CREATE_BUG */
  2149.       free (redirectee_word);
  2150.  
  2151.       if (fd < 0 )
  2152.     return (errno);
  2153.  
  2154.       if (for_real)
  2155.     {
  2156.       if (remembering)
  2157.         /* Only setup to undo it if the thing to undo is active. */
  2158.         if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
  2159.           add_undo_redirect (redirector);
  2160.         else
  2161.           add_undo_close_redirect (redirector);
  2162.  
  2163.       if ((fd != redirector) && (dup2 (fd, redirector) < 0))
  2164.         return (errno);
  2165.  
  2166.       /*
  2167.        * If we're remembering, then this is the result of a while, for
  2168.        * or until loop with a loop redirection, or a function/builtin
  2169.        * executing in the parent shell with a redirection.  In the
  2170.        * function/builtin case, we want to set all file descriptors > 2
  2171.        * to be close-on-exec to duplicate the effect of the old
  2172.        * for i = 3 to NOFILE close(i) loop.  In the case of the loops,
  2173.        * both sh and ksh leave the file descriptors open across execs.
  2174.        * The Posix standard mentions only the exec builtin.
  2175.        */
  2176.       if (set_clexec && (redirector > 2))
  2177.         SET_CLOSE_ON_EXEC (redirector);
  2178.     }
  2179.       if (fd != redirector)
  2180.     close (fd);        /* Don't close what we just opened! */
  2181.  
  2182.       /* If we are hacking both stdout and stderr, do the stderr
  2183.      redirection here. */
  2184.       if (ri == r_err_and_out)
  2185.     {
  2186.       if (for_real)
  2187.         {
  2188.           if (remembering)
  2189.         add_undo_redirect (2);
  2190.           if (dup2 (1, 2) < 0)
  2191.         return (errno);
  2192.         }
  2193.     }
  2194.       break;
  2195.  
  2196.     case r_reading_until:
  2197.     case r_deblank_reading_until:
  2198.       {
  2199.     /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
  2200.        the new input.  Place it in a temporary file. */
  2201.     int document_index = 0;
  2202.     char *document = (char *)NULL;
  2203.  
  2204.     /* Expand the text if the word that was specified had no quoting.
  2205.        Note that the text that we expand is treated exactly as if it
  2206.        were surrounded by double-quotes.  */
  2207.  
  2208.     if (!redirectee)
  2209.       document = savestring ("");
  2210.     else
  2211.       {
  2212.         if (!redirectee->quoted)
  2213.           {
  2214.         WORD_LIST *temp_word_list =
  2215.           (WORD_LIST *)expand_string (redirectee->word,
  2216.                           Q_HERE_DOCUMENT);
  2217.  
  2218.         document = string_list (temp_word_list);
  2219.         if (!document)
  2220.           document = savestring ("");
  2221.         dispose_words (temp_word_list);
  2222.           }
  2223.         else
  2224.           {
  2225.         document = redirectee->word;
  2226.           }
  2227.         document_index = strlen (document);
  2228.  
  2229.         {
  2230.           char filename[40];
  2231.           pid_t pid = getpid ();
  2232.  
  2233.           /* Make the filename for the temp file. */
  2234.           sprintf (filename, "/tmp/t%d-sh", pid);
  2235.  
  2236.           fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
  2237.           if (fd < 0)
  2238.         {
  2239.           if (!redirectee->quoted)
  2240.             free (document);
  2241.           return (errno);
  2242.         }
  2243.  
  2244.           write (fd, document, document_index);
  2245.           close (fd);
  2246.  
  2247.           if (!redirectee->quoted)
  2248.         free (document);
  2249.  
  2250.           /* Make the document really temporary.  Also make it the
  2251.          input. */
  2252.           fd = open (filename, O_RDONLY, 0666);
  2253.  
  2254.           if (unlink (filename) < 0 || fd < 0)
  2255.         return (errno);
  2256.  
  2257.           if (for_real)
  2258.         {
  2259.           if (remembering)
  2260.             /* Only setup to undo it if the thing to undo is active. */
  2261.             if ((fd != redirector) &&
  2262.             (fcntl (redirector, F_GETFD, 0) != -1))
  2263.               add_undo_redirect (redirector);
  2264.             else
  2265.               add_undo_close_redirect (redirector);
  2266.  
  2267.           if (dup2 (fd, redirector) < 0)
  2268.             return (errno);
  2269.  
  2270.           if (set_clexec && (redirector > 2))
  2271.             SET_CLOSE_ON_EXEC (redirector);
  2272.         }
  2273.           close (fd);
  2274.         }
  2275.       }
  2276.       }
  2277.       break;
  2278.  
  2279.     case r_duplicating_input:
  2280.     case r_duplicating_output:
  2281.       if (for_real)
  2282.     {
  2283.       if (remembering)
  2284.         /* Only setup to undo it if the thing to undo is active. */
  2285.         if (((int)redirectee != redirector) &&
  2286.         (fcntl (redirector, F_GETFD, 0) != -1))
  2287.           add_undo_redirect (redirector);
  2288.         else
  2289.           add_undo_close_redirect (redirector);
  2290.  
  2291.       /* This is correct.  2>&1 means dup2 (1, 2); */
  2292.       if (dup2 ((int)redirectee, redirector) < 0)
  2293.         return (errno);
  2294.  
  2295.       /* First duplicate the close-on-exec state of redirectee.  dup2
  2296.          leaves the flag unset on the new descriptor, which means it
  2297.          stays open.  Only set the close-on-exec bit for file descriptors
  2298.          greater than 2 in any case, since 0-2 should always be open
  2299.          unless closed by something like `exec 2<&-'. */
  2300.       /* if ((already_set || set_unconditionally) && (ok_to_set))
  2301.         set_it () */
  2302.       if (((fcntl ((int)redirectee, F_GETFD, 0) == 1) || set_clexec) &&
  2303.            (redirector > 2))
  2304.         SET_CLOSE_ON_EXEC (redirector);
  2305.     }
  2306.       break;
  2307.  
  2308.     case r_close_this:
  2309.       if (for_real)
  2310.     {
  2311.       if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
  2312.         add_undo_redirect (redirector);
  2313.  
  2314.       close (redirector);
  2315.     }
  2316.       break;
  2317.     }
  2318.   return (0);
  2319. }
  2320.  
  2321. #define SHELL_FD_BASE    10
  2322.  
  2323. /* Remember the file descriptor associated with the slot FD,
  2324.    on REDIRECTION_UNDO_LIST.  Note that the list will be reversed
  2325.    before it is executed. */
  2326. static int
  2327. add_undo_redirect (fd)
  2328.      int fd;
  2329. {
  2330.   int new_fd, clexec_flag;
  2331.   REDIRECT *new_redirect, *closer;
  2332.  
  2333.   new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
  2334.  
  2335.   if (new_fd < 0)
  2336.     {
  2337.       file_error ("redirection error");
  2338.       return (-1);
  2339.     }
  2340.   else
  2341.     {
  2342.       clexec_flag = fcntl (fd, F_GETFD, 0);
  2343.       closer = make_redirection (new_fd, r_close_this, 0);
  2344.       new_redirect = make_redirection (fd, r_duplicating_output, new_fd);
  2345.       new_redirect->next = closer;
  2346.       closer->next = redirection_undo_list;
  2347.       redirection_undo_list = new_redirect;
  2348.       /*
  2349.        * File descriptors used only for saving others should always be
  2350.        * marked close-on-exec.  Unfortunately, we have to preserve the
  2351.        * close-on-exec state of the file descriptor we are saving, since
  2352.        * fcntl (F_DUPFD) sets the new file descriptor to remain open
  2353.        * across execs.  If, however, the file descriptor whose state we
  2354.        * are saving is <= 2, we can just set the close-on-exec flag,
  2355.        * because file descriptors 0-2 should always be open-on-exec,
  2356.        * and the restore above in do_redirection() will take care of it.
  2357.        */
  2358.       if (clexec_flag || fd < 3)
  2359.     SET_CLOSE_ON_EXEC (new_fd);
  2360.     }
  2361.   return (0);
  2362. }
  2363.  
  2364. /* Set up to close FD when we are finished with the current command
  2365.    and its redirections. */
  2366. static void
  2367. add_undo_close_redirect (fd)
  2368.      int fd;
  2369. {
  2370.   REDIRECT *closer;
  2371.  
  2372.   closer = make_redirection (fd, r_close_this, 0);
  2373.   closer->next = redirection_undo_list;
  2374.   redirection_undo_list = closer;
  2375. }
  2376.  
  2377. intern_function (name, function)
  2378.      WORD_DESC *name;
  2379.      COMMAND *function;
  2380. {
  2381.   SHELL_VAR *var;
  2382.  
  2383.   if (!check_identifier (name))
  2384.     return (EXECUTION_FAILURE);
  2385.  
  2386.   var = find_function (name->word);
  2387.   if (var && readonly_p (var))
  2388.     {
  2389.       report_error ("%s: readonly function", var->name);
  2390.       return (EXECUTION_FAILURE);
  2391.     }
  2392.  
  2393.   bind_function (name->word, function);
  2394.   return (EXECUTION_SUCCESS);
  2395. }
  2396.  
  2397. /* Make sure that identifier is a valid shell identifier, i.e.
  2398.    does not contain a dollar sign, nor is quoted in any way.  Nor
  2399.    does it consist of all digits. */
  2400. check_identifier (word)
  2401.      WORD_DESC *word;
  2402. {
  2403.   if (word->dollar_present || word->quoted || all_digits (word->word))
  2404.     {
  2405.       report_error ("`%s' is not a valid identifier", word->word);
  2406.       return (0);
  2407.     }
  2408.   else
  2409.     return (1);
  2410. }
  2411.  
  2412. #define u_mode_bits(x) (((x) & 0000700) >> 6)
  2413. #define g_mode_bits(x) (((x) & 0000070) >> 3)
  2414. #define o_mode_bits(x) (((x) & 0000007) >> 0)
  2415. #define X_BIT(x) (x & 1)
  2416.  
  2417. /* Return some flags based on information about this file.
  2418.    The EXISTS bit is non-zero if the file is found.
  2419.    The EXECABLE bit is non-zero the file is executble.
  2420.    Zero is returned if the file is not found. */
  2421. int
  2422. file_status (name)
  2423.      char *name;
  2424. {
  2425.   struct stat finfo;
  2426.   static int user_id = -1;
  2427.  
  2428.   /* Determine whether this file exists or not. */
  2429.   if (stat (name, &finfo) < 0)
  2430.     return (0);
  2431.  
  2432.   /* If the file is a directory, then it is not "executable" in the
  2433.      sense of the shell. */
  2434.   if (S_ISDIR (finfo.st_mode))
  2435.     return (FS_EXISTS);
  2436.  
  2437.   /* Find out if the file is actually executable.  By definition, the
  2438.      only other criteria is that the file has an execute bit set that
  2439.      we can use. */
  2440.   if (user_id == -1)
  2441.     user_id = geteuid ();
  2442.  
  2443.   /* Root only requires execute permission for any of owner, group or
  2444.      others to be able to exec a file. */
  2445.   if (user_id == 0)
  2446.     {
  2447.       int bits;
  2448.  
  2449.       bits = (u_mode_bits (finfo.st_mode) |
  2450.           g_mode_bits (finfo.st_mode) |
  2451.           o_mode_bits (finfo.st_mode));
  2452.  
  2453.       if (X_BIT (bits))
  2454.     return (FS_EXISTS | FS_EXECABLE);
  2455.     }
  2456.  
  2457.   /* If we are the owner of the file, the owner execute bit applies. */
  2458.   if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
  2459.     return (FS_EXISTS | FS_EXECABLE);
  2460.  
  2461.   /* If we are in the owning group, the group permissions apply. */
  2462.   if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
  2463.     return (FS_EXISTS | FS_EXECABLE);
  2464.  
  2465.   /* If `others' have execute permission to the file, then so do we,
  2466.      since we are also `others'. */
  2467.   if (X_BIT (o_mode_bits (finfo.st_mode)))
  2468.     return (FS_EXISTS | FS_EXECABLE);
  2469.   else
  2470.     return (FS_EXISTS);
  2471. }
  2472.  
  2473. /* Return non-zero if FILE exists and is executable.
  2474.    Note that this function is the definition of what an
  2475.    executable file is; do not change this unless YOU know
  2476.    what an executable file is. */
  2477. int
  2478. executable_file (file)
  2479.      char *file;
  2480. {
  2481.   if (file_status (file) & FS_EXECABLE)
  2482.     return (1);
  2483.   else
  2484.     return (0);
  2485. }
  2486.  
  2487. /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
  2488.    encounters a `.' as the directory pathname while scanning the
  2489.    list of possible pathnames; i.e., if `.' comes before the directory
  2490.    containing the file of interest. */
  2491. int dot_found_in_search = 0;
  2492.  
  2493. /* Locate the executable file referenced by NAME, searching along
  2494.    the contents of the shell PATH variable.  Return a new string
  2495.    which is the full pathname to the file, or NULL if the file
  2496.    couldn't be found.  If a file is found that isn't executable,
  2497.    and that is the only match, then return that. */
  2498. char *
  2499. find_user_command (name)
  2500.      char *name;
  2501. {
  2502.   return (find_user_command_internal (name, FS_EXEC_PREFERRED));
  2503. }
  2504.  
  2505. /* Locate the file referenced by NAME, searching along the contents
  2506.    of the shell PATH variable.  Return a new string which is the full
  2507.    pathname to the file, or NULL if the file couldn't be found.  This
  2508.    returns the first file found. */
  2509. char *
  2510. find_path_file (name)
  2511.      char *name;
  2512. {
  2513.   return (find_user_command_internal (name, FS_EXISTS));
  2514. }
  2515.  
  2516. static char *
  2517. find_user_command_internal (name, flags)
  2518.      char *name;
  2519.      int flags;
  2520. {
  2521.   char *path_list;
  2522.  
  2523.   path_list = get_string_value ("PATH");
  2524.  
  2525.   if (!path_list)
  2526.     return (savestring (name));
  2527.  
  2528.   return (find_user_command_in_path (name, path_list, flags));
  2529. }
  2530.  
  2531. /* Return the next element from PATH_LIST, a colon separated list of
  2532.    paths.  PATH_INDEX_POINTER is the address of an index into PATH_LIST;
  2533.    the index is modified by this function.
  2534.    Return the next element of PATH_LIST or NULL if there are no more. */
  2535. static char *
  2536. get_next_path_element (path_list, path_index_pointer)
  2537.      char *path_list;
  2538.      int *path_index_pointer;
  2539. {
  2540.   extern char *extract_colon_unit ();
  2541.   char *path;
  2542.  
  2543.   path = extract_colon_unit (path_list, path_index_pointer);
  2544.  
  2545.   if (!path)
  2546.     return (path);
  2547.  
  2548.   if (!*path)
  2549.     {
  2550.       free (path);
  2551.       path = savestring (".");
  2552.     }
  2553.  
  2554.   return (path);
  2555. }
  2556.  
  2557. char *
  2558. user_command_matches (name, flags, state)
  2559.      char *name;
  2560.      int flags, state;
  2561. {
  2562.   register int i;
  2563.   char *path_list;
  2564.   int  path_index;
  2565.   char *path_element;
  2566.   char *match;
  2567.   static char **match_list = NULL;
  2568.   static int match_list_size = 0;
  2569.   static int match_index = 0;
  2570.  
  2571.   if (!state)
  2572.     {
  2573.       /* Create the list of matches. */
  2574.       if (!match_list)
  2575.     {
  2576.       match_list =
  2577.         (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
  2578.  
  2579.       for (i = 0; i < match_list_size; i++)
  2580.         match_list[i] = 0;
  2581.     }
  2582.  
  2583.       /* Clear out the old match list. */
  2584.       for (i = 0; i < match_list_size; i++)
  2585.     match_list[i] = NULL;
  2586.  
  2587.       /* We haven't found any files yet. */
  2588.       match_index = 0;
  2589.  
  2590.       path_list = get_string_value ("PATH");
  2591.       path_index = 0;
  2592.  
  2593.       while (path_list && path_list[path_index])
  2594.     {
  2595.       char *find_user_command_in_path ();
  2596.  
  2597.       path_element = get_next_path_element (path_list, &path_index);
  2598.  
  2599.       if (!path_element)
  2600.         break;
  2601.  
  2602.       match = find_user_command_in_path (name, path_element, flags);
  2603.  
  2604.       free (path_element);
  2605.  
  2606.       if (!match)
  2607.         continue;
  2608.  
  2609.       if (match_index + 1 == match_list_size)
  2610.         match_list = (char **)xrealloc
  2611.           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
  2612.       match_list[match_index++] = match;
  2613.       match_list[match_index] = (char *)NULL;
  2614.     }
  2615.  
  2616.       /* We haven't returned any strings yet. */
  2617.       match_index = 0;
  2618.     }
  2619.  
  2620.   match = match_list[match_index];
  2621.  
  2622.   if (match)
  2623.     match_index++;
  2624.  
  2625.   return (match);
  2626. }
  2627.  
  2628. /* Return 1 if PATH1 and PATH2 are the same file.  This is kind of
  2629.    expensive.  If non-NULL STP1 and STP2 point to stat structures
  2630.    corresponding to PATH1 and PATH2, respectively. */
  2631. int
  2632. same_file (path1, path2, stp1, stp2)
  2633.      char *path1, *path2;
  2634.      struct stat *stp1, *stp2;
  2635. {
  2636.   struct stat st1, st2;
  2637.  
  2638.   if (stp1 == NULL)
  2639.     {
  2640.       if (stat (path1, &st1) != 0)
  2641.     return (0);
  2642.       stp1 = &st1;
  2643.     }
  2644.  
  2645.   if (stp2 == NULL)
  2646.     {
  2647.       if (stat (path2, &st2) != 0)
  2648.     return (0);
  2649.       stp2 = &st2;
  2650.     }
  2651.  
  2652.   return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
  2653. }
  2654.  
  2655. /* This does the dirty work for find_path_file () and find_user_command ().
  2656.    NAME is the name of the file to search for.
  2657.    PATH_LIST is a colon separated list of directories to search.
  2658.    FLAGS contains bit fields which control the files which are eligible.
  2659.    Some values are:
  2660.       FS_EXEC_ONLY:        The file must be an executable to be found.
  2661.       FS_EXEC_PREFERRED:    If we can't find an executable, then the
  2662.                 the first file matching NAME will do.
  2663.       FS_EXISTS:        The first file found will do.
  2664. */
  2665. static char *
  2666. find_user_command_in_path (name, path_list, flags)
  2667.      char *name;
  2668.      char *path_list;
  2669.      int flags;
  2670. {
  2671.   char *full_path, *path, *file_to_lose_on;
  2672.   int status, path_index, name_len;
  2673.   struct stat finfo;
  2674.  
  2675.   name_len = strlen (name);
  2676.  
  2677.   /* The file name which we would try to execute, except that it isn't
  2678.      possible to execute it.  This is the first file that matches the
  2679.      name that we are looking for while we are searching $PATH for a
  2680.      suitable one to execute.  If we cannot find a suitable executable
  2681.      file, then we use this one. */
  2682.   file_to_lose_on = (char *)NULL;
  2683.  
  2684.   /* We haven't started looking, so we certainly haven't seen
  2685.      a `.' as the directory path yet. */
  2686.   dot_found_in_search = 0;
  2687.  
  2688.   if (absolute_program (name))
  2689.     {
  2690.       full_path = (char *)xmalloc (1 + name_len);
  2691.       strcpy (full_path, name);
  2692.  
  2693.       status = file_status (full_path);
  2694.  
  2695.       if (!(status & FS_EXISTS))
  2696.     return (0);
  2697.  
  2698.       if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
  2699.     return (full_path);
  2700.       else
  2701.     {
  2702.       free (full_path);
  2703.       return ((char *)NULL);
  2704.     }
  2705.     }
  2706.  
  2707.   /* Find out the location of the current working directory. */
  2708.   stat (".", &finfo);
  2709.  
  2710.   path_index = 0;
  2711.   while (path_list && path_list[path_index])
  2712.     {
  2713.       /* Allow the user to interrupt out of a lengthy path search. */
  2714.       QUIT;
  2715.  
  2716.       path = get_next_path_element (path_list, &path_index);
  2717.  
  2718.       if (!path)
  2719.     break;
  2720.  
  2721.       if (*path == '~')
  2722.     {
  2723.       char *tilde_expand ();
  2724.       char *t = tilde_expand (path);
  2725.       free (path);
  2726.       path = t;
  2727.     }
  2728.  
  2729.       /* Remember the location of "." in the path, in all its forms
  2730.      (as long as they begin with a `.', e.g. `./.') */
  2731.       if ((*path == '.') &&
  2732.       same_file (".", path, &finfo, (struct stat *)NULL))
  2733.     dot_found_in_search = 1;
  2734.  
  2735.       full_path = (char *)xmalloc (2 + strlen (path) + name_len);
  2736.       sprintf (full_path, "%s/%s", path, name);
  2737.       free (path);
  2738.  
  2739.       status = file_status (full_path);
  2740.  
  2741.       if (!(status & FS_EXISTS))
  2742.     goto next_file;
  2743.  
  2744.       /* The file exists.  If the caller simply wants the first file,
  2745.      here it is. */
  2746.       if (flags & FS_EXISTS)
  2747.     return (full_path);
  2748.  
  2749.        /* If the file is executable, then it satisfies the cases of
  2750.       EXEC_ONLY and EXEC_PREFERRED.  Return this file unconditionally. */
  2751.       if (status & FS_EXECABLE)
  2752.     {
  2753.       if (file_to_lose_on)
  2754.         free (file_to_lose_on);
  2755.  
  2756.       return (full_path);
  2757.     }
  2758.  
  2759.       /* The file is not executable, but it does exist.  If we prefer
  2760.      an executable, then remember this one if it is the first one
  2761.      we have found. */
  2762.       if (flags & FS_EXEC_PREFERRED)
  2763.     {
  2764.       if (!file_to_lose_on)
  2765.         file_to_lose_on = savestring (full_path);
  2766.     }
  2767.  
  2768.     next_file:
  2769.       free (full_path);
  2770.     }
  2771.  
  2772.   /* We didn't find exactly what the user was looking for.  Return
  2773.      the contents of FILE_TO_LOSE_ON which is NULL when the search
  2774.      required an executable, or non-NULL if a file was found and the
  2775.      search would accept a non-executable as a last resort. */
  2776.   return (file_to_lose_on);
  2777. }
  2778.  
  2779. /* Given a string containing units of information separated by colons,
  2780.    return the next one pointed to by INDEX, or NULL if there are no more.
  2781.    Advance INDEX to the character after the colon. */
  2782. char *
  2783. extract_colon_unit (string, index)
  2784.      char *string;
  2785.      int *index;
  2786. {
  2787.   int i, start;
  2788.  
  2789.   i = *index;
  2790.  
  2791.   if (!string || (i >= strlen (string)))
  2792.     return ((char *)NULL);
  2793.  
  2794.   /* Each call to this routine leaves the index pointing at a colon if
  2795.      there is more to the path.  If I is > 0, then increment past the
  2796.      `:'.  If I is 0, then the path has a leading colon.  Trailing colons
  2797.      are handled OK by the `else' part of the if statement; an empty
  2798.      string is returned in that case. */
  2799.   if (i && string[i] == ':')
  2800.     i++;
  2801.  
  2802.   start = i;
  2803.  
  2804.   while (string[i] && string[i] != ':') i++;
  2805.  
  2806.   *index = i;
  2807.  
  2808.   if (i == start)
  2809.     {
  2810.       if (string[i])
  2811.     (*index)++;
  2812.  
  2813.       /* Return "" in the case of a trailing `:'. */
  2814.       return (savestring (""));
  2815.     }
  2816.   else
  2817.     {
  2818.       char *value;
  2819.  
  2820.       value = (char *)xmalloc (1 + (i - start));
  2821.       strncpy (value, &string[start], (i - start));
  2822.       value [i - start] = '\0';
  2823.  
  2824.       return (value);
  2825.     }
  2826. }
  2827.  
  2828. /* Return non-zero if the characters from SAMPLE are not all valid
  2829.    characters to be found in the first line of a shell script.  We
  2830.    check up to the first newline, or SAMPLE_LEN, whichever comes first.
  2831.    All of the characters must be printable or whitespace. */
  2832.  
  2833. #if !defined (isspace)
  2834. #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
  2835. #endif
  2836.  
  2837. #if !defined (isprint)
  2838. #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
  2839. #endif
  2840.  
  2841. int
  2842. check_binary_file (sample, sample_len)
  2843.      unsigned char *sample;
  2844.      int sample_len;
  2845. {
  2846.   register int i;
  2847.  
  2848.   for (i = 0; i < sample_len; i++)
  2849.     {
  2850.       if (sample[i] == '\n')
  2851.     break;
  2852.  
  2853.       if (!isspace (sample[i]) && !isprint (sample[i]))
  2854.     return (1);
  2855.     }
  2856.   return (0);
  2857. }
  2858.